package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class LoginCheckInterceptorDemo implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle 拦截");
        //1.获取url
        StringBuffer url = request.getRequestURL();
        log.info("请求路径：{}",url);
        //2.获取token并判断token是否为空，为空时返回错误信息
        String token = request.getHeader("token");
        log.info("请求的令牌：{}",token);
        if(!StringUtils.hasLength(token)){
            log.info("token不存在");
            Result result = Result.error("NOT_LOGIN");
            //讲String类型转换为json格式
            String json = JSONObject.toJSONString(result);
            //设置响应头（告知浏览器，响应数据结果类型为json，编码为utf-8
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);
            return false;
        }
        //3.解析token解析异常时返回错误信息
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("令牌解析失败");
            Result result = Result.error("NOT_LOGIN");
            //讲Result类型转换为json格式
            String json = JSONObject.toJSONString(result);
            //设置响应头（告知浏览器，响应数据结果类型为json，编码为utf-8
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);
            return false;
        }

        //4.放行

        return true;
    }
}
